package cn.dazhou.wificonnectdemo.wifi

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import cn.dazhou.wificonnectdemo.Timber
import cn.dazhou.wificonnectdemo.wifiName
import cn.dazhou.wificonnectdemo.wifiPwd

/** wifi扫描结果接收器，用于接收wifi扫描结果 */
object WifiScanResultReceiver : BroadcastReceiver() {

    @SuppressLint("MissingPermission")
    override fun onReceive(context: Context, intent: Intent) {
        if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION == intent.action) {
            val scanResults = WifiUtil.wifiManager.scanResults
            Timber.fi("收到wifi扫描结果: ${scanResults?.size}, 想要连接的wifi是：$wifiName")

            // 扫描到结果后，10秒后又再次扫描
            WifiScanHandler.delayScan()


            Timber.fi("${WifiUtil.getWifiName()} ${if (WifiUtil.isWifiConnected()) "已连接" else "未连接"}")
            if (WifiUtil.isWifiConnected() && WifiUtil.getWifiName() == wifiName) {
                Timber.fi("需要的Wifi(${wifiName})本来就连接好了")
                return
            }

            if (scanResults == null || scanResults.size == 0) {
                return
            }

            for (scanResult in scanResults) {
//                Timber.fi("扫描到wifi：${scanResult.SSID}")
                if (scanResult.SSID == wifiName) {
                    Timber.fi("扫描到指定的Wifi了：$wifiName")
                    WifiUtil.connectToWiFi(wifiName, wifiPwd)
                    break
                }
            }
        }
    }

}